import { defineStore } from 'pinia'

type ThemeMode = 'light' | 'dark' | 'auto'

interface CustomColors {
  primary: string
  success: string
  warning: string
  danger: string
}

interface ThemeState {
  currentTheme: ThemeMode
  systemTheme: 'light' | 'dark'
  customColors: CustomColors
}

export const useThemeStore = defineStore('theme', {
  state: (): ThemeState => ({
    currentTheme: 'auto',
    systemTheme: 'light',
    customColors: {
      primary: '#409EFF',
      success: '#67C23A',
      warning: '#E6A23C',
      danger: '#F56C6C'
    }
  }),

  getters: {
    isDark: (state: ThemeState) => {
      if (state.currentTheme === 'auto') {
        return state.systemTheme === 'dark'
      }
      return state.currentTheme === 'dark'
    },
    
    effectiveTheme: (state: ThemeState) => {
      if (state.currentTheme === 'auto') {
        return state.systemTheme
      }
      return state.currentTheme
    }
  },

  actions: {
    // 初始化主题
    async initTheme() {
      // 从本地存储读取主题设置
      const savedTheme = localStorage.getItem('theme') as ThemeMode
      if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
        this.currentTheme = savedTheme
      }

      // 从本地存储读取自定义颜色
      const savedColors = localStorage.getItem('customColors')
      if (savedColors) {
        try {
          this.customColors = { ...this.customColors, ...JSON.parse(savedColors) }
        } catch (error) {
          console.error('解析自定义颜色失败:', error)
        }
      }

      // 监听系统主题变化
      this.watchSystemTheme()
      
      // 应用主题
      this.applyTheme()
    },

    // 设置主题
    setTheme(theme: ThemeMode) {
      if (!['light', 'dark', 'auto'].includes(theme)) {
        console.error('无效的主题:', theme)
        return
      }

      this.currentTheme = theme
      localStorage.setItem('theme', theme)
      this.applyTheme()
    },

    // 设置自定义颜色
    setCustomColor(colorType: keyof CustomColors, color: string) {
      if (!color || !colorType) return

      this.customColors[colorType] = color
      localStorage.setItem('customColors', JSON.stringify(this.customColors))
      this.applyCustomColors()
    },

    // 批量设置自定义颜色
    setCustomColors(colors: Partial<CustomColors>) {
      this.customColors = { ...this.customColors, ...colors }
      localStorage.setItem('customColors', JSON.stringify(this.customColors))
      this.applyCustomColors()
    },

    // 监听系统主题变化
    watchSystemTheme() {
      // 获取初始系统主题
      this.systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'

      // 监听系统主题变化
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', (e) => {
        this.systemTheme = e.matches ? 'dark' : 'light'
        if (this.currentTheme === 'auto') {
          this.applyTheme()
        }
      })
    },

    // 应用主题
    applyTheme() {
      const theme = this.effectiveTheme
      const root = document.documentElement

      // 设置主题属性
      root.setAttribute('data-theme', theme)
      
      // 更新 Element Plus 主题
      if (theme === 'dark') {
        root.classList.add('dark')
      } else {
        root.classList.remove('dark')
      }

      // 应用自定义颜色
      this.applyCustomColors()
    },

    // 应用自定义颜色
    applyCustomColors() {
      const root = document.documentElement
      
      Object.entries(this.customColors).forEach(([key, value]) => {
        root.style.setProperty(`--el-color-${key}`, value)
        root.style.setProperty(`--${key}-color`, value)
      })
    },

    // 重置主题设置
    resetTheme() {
      this.currentTheme = 'auto'
      this.customColors = {
        primary: '#409EFF',
        success: '#67C23A',
        warning: '#E6A23C',
        danger: '#F56C6C'
      }
      
      localStorage.removeItem('theme')
      localStorage.removeItem('customColors')
      
      this.applyTheme()
    }
  }
})